/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： JdbcServiceImpl.java
 * Date：18-11-5 上午10:54
 * Author: guomw
 */

package com.guomw.report.service.service.upgrade;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author guomw
 * @date 2018/9/11
 */
@Service
public class JdbcServiceImpl implements JdbcService {
    private static final Log log = LogFactory.getLog(JdbcServiceImpl.class);

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private EntityManager entityManager;

    @Override
    public void runJdbcWork(ConnectionConsumer connectionConsumer) throws SQLException, IOException {
        log.debug("Prepare to run jdbc");
        Connection connection = entityManager.unwrap(Connection.class);
        if (connection == null) {
            throw new IllegalStateException("@Transactional did not work check DataSupportConfig for details.");
        }
        connectionConsumer.workWithConnection(new SimpleConnectionProvider(connection));
        log.debug("End jdbc");
    }

    @Override
    public void runStandaloneJdbcWork(ConnectionConsumer connectionConsumer) throws SQLException, IOException {
        log.debug("Prepare to run jdbc");
        Connection connection = entityManager.unwrap(Connection.class);
        if (connection==null){
            connectionConsumer.workWithConnection(null);
        }else{
            connectionConsumer.workWithConnection(new SimpleConnectionProvider(connection));
        }
        log.debug("End jdbc");
    }
}
